package Verktoy;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class SendMail{// implements Runnable {

    /**
     * Adresser og porter til gmail.com's mailtjener. Mailadressen er opprettet for prosjektet.
     */
    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final int SMTP_HOST_PORT = 465;
    private static final String SMTP_AUTH_USER = "askme.hist@gmail.com";
    private static final String SMTP_AUTH_PWD  = "gjemgjem";
    private String recipient;
    private String subject;
    private String bodytext;

    public SendMail(String emailAddress, String bodytext, String subject){
        super();
        this.recipient = emailAddress;
        this.subject = subject;
        this.bodytext = bodytext;
    }

    /**
     * Setter et par properties vi trenger for vårt oppsett av SMTP-serveren.
     * Oppretter et mailsession og en epost-melding som tar i bruk objektvariablene,
     * og sender eposten til SMTP-serveren.
     */
    public void run() {
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", SMTP_HOST_NAME);
        props.put("mail.smtps.auth", "true");

        Session mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(false);
        try{
        Transport transport = mailSession.getTransport();

        /*
         * Her setter vi tittel og innhold på vår nye mail.
         */
        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        message.setContent(bodytext, "text/plain");

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        transport.connect
          (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();
        } catch (Exception e) {
            System.out.println("Mail ikke sendt: "+e);
        }
    }
}